<template>
    <div id="map">
        <div id="top">
            <div class="Tips"></div>
            <!-- time和distance -->
            <div id="timesAdistance"></div>
            <!-- 转向牌 -->
            <div id="turnTips">
                <img src="/img/tips/ZHI.png" id="turnTipsZHI" v-if="isShowStraight" alt="">
                <img src="/img/tips/ZUO.png" id="turnTipsZUO" v-if="isShowLeft" alt="">
                <img src="/img/tips/YOU.png" id="turnTipsYOU" v-if="isShowRight" alt="">
            </div>
        </div>

        <div id="btnControl">
            <div v-if="isShowRoutePanel">
                <button @click="setStart">设置起点</button>
                <button @click="setEnd">设置终点</button>
                <button @click="roadAnalysisTest">路径分析</button>
                <button @click="imitateNavigation">模拟导航</button>
                <button @click="mNavigation">真实导航</button>
                <button @click="changeMap">改变地图</button>
            </div>
            <div v-if="isShowNavConPanel">
                <button @click="imitateStop">暂停导航</button>
                <button @click="setEnd">继续导航</button>
                <button @click="imitateDel">退出导航</button>
            </div>
        </div>


        <!-- 实s时位置 -->
        <!--<div id="me"-->
        <!--style="position: absolute;bottom:30px;left:10px;z-index: 99999;width: 80px;min-height: 10px;background: #000;color:#fff">-->
        <!--</div>-->
        <!--<div id="barControl">-->

        <!--</div>-->

    </div>

</template>

<script>
    import axios from 'axios'; // 引入axios
    import mapboxgl from "mapbox-gl";
    import "mapbox-gl/dist/mapbox-gl.css";
    import '../../public/js/leaflet/leaflet-mapbox-gl.js'
    import 'leaflet/dist/leaflet.css'
    import * as L from 'leaflet'
    import $ from 'jquery'
    import QS from 'qs'; // 引入qs模块


    import {basicMap, streetStyleMap, fiordStyleMap, nightStyleMap} from "../config/mapdata.js"

    export default {
        name: "Map",
        data() {
            return {
                roadNetHost: "http://192.168.0.121:3000",
                map: this.$rootMap.map,
                mapboxLayer:null,
                myIcon: L.icon({
                    iconUrl: require('../assets/marker-icon.png'),
                    iconSize: [24, 36],
                    iconAnchor: [12, 36],
                    popupAnchor: [-3, -76]
                }),
                pointsLayer: null,
                linesLayer: null,
                layergroup: null,
                zoom: 3,
                isShowRoutePanel: true,
                isShowNavConPanel: false,
                isShowTips: false,
                isShowStraight: false,
                isShowLeft: false,
                isShowRight: false,
                startPoint: null,
                wayPoint: null,
                barrierPoint: null,
                endPoint: null,
                imitatePointList: [],
                imitateGuides: [],
                imitateRoutes: [],
                imitatePoint: null,//移动的marker
                imitateTime: null,//计时器
                lastLine: null,

            }
        },
        mounted() {
            // this.addDataToMap();
            this.initMap();
        },
        methods: {
            initMap() {
                this.map = L.map('map', {
                    center: [31.86705, 118.79619],
                    zoom: 10,
                });
                this.mapboxLayer = L.mapboxGL({
                    style: "http://192.168.0.120:8088/styles/night/style.json",
                    center: [118.79619, 31.86705],
                    zoom: 10,
                    antialias: false,
                    pitch: 50
                }).addTo(this.map);



                // this.map = new mapboxgl.Map({
                //     container: 'map',
                //     style: "http://192.168.0.121:5095/bdgis/mapstyle/basic-style.json",
                //     center: [118.79619, 31.86705],
                //     zoom: 10,
                //     antialias: false,
                //     pitch: 50
                // });

                mapboxMap._addMarker();


                // let nav = new mapboxgl.NavigationControl();
                // this.map.addControl(nav,'bottom-left');
                // let scale = new mapboxgl.ScaleControl({
                //     maxWidth:80,
                //     unit:'imperial'
                // });
                // this.map.addControl(scale);
                // scale.setUnit('metric');
            },
            changeMap(){
                this.mapboxLayer._setStyle("http://192.168.0.120:8088/styles/basic/style.json")
            },
            // 请求路网数据
            async getRoleData() {
                let data;
                await axios({
                    url: this.roadNetHost + "/iserver/services/mgs-networkanalyst/rest/domainComponents/NetworkAnalystServiceImpl/getFeaturesResult.json",
                    method: "GET",
                    params: {
                        arg0: {
                            "datasetName": 'Rnanjing_Network',
                            "datasourceName": 'Rnanjing'
                        }
                    }
                }).then(res => {
                    data = res.data.result;
                }).catch();
                return data;
            },
            async roadAnalysisTest() {
                let data = {
                    "isUsingRoad": 1,
                    "isReturnGuide": 1,
                    "nodes": [{"latitude": this.startPoint._lngLat.lat, "longitude": this.startPoint._lngLat.lng}, {
                        "latitude": this.endPoint._lngLat.lat,
                        "longitude": this.endPoint._lngLat.lng
                    }]
                };
                await axios.post('http://192.168.0.121:5080/bdgis/route', data).then(res => {
                    console.log(res);
                }).catch(e => {
                    console.log(e);
                });
                return data;
            },
            async addDataToMap() {

                let data = await this.getRoleData();
                console.log(data);

                // this.map.addSource('route',{
                //     'type':'geojson',
                //     'data':{
                //         'type':'FeatureCollection',
                //         'features':data.linelist
                //     }
                // });
                // this.map.addLayer({
                //     id: 'route1',
                //     type: 'line',
                //     source:'route',
                //     layout: {},
                //     paint: {
                //         'line-color': '#888',
                //         'line-width': 3
                //     }
                // });
                // this.linesLayer = L.geoJSON(data.linelist, {
                //     style: feature => {
                //         return {
                //             color: 'rgba(50,50,50,1)',
                //             weight: 2
                //         };
                //     }
                // }).addTo(this.map);
                // this.pointsLayer = L.geoJSON(data.pointlist, {
                //     pointToLayer: function (geoJsonPoint, latlng) {
                //         let cir = L.circleMarker(latlng, {
                //             fill: 'rgb(0,0,0)',
                //             radius: 1,
                //             color: '#000',
                //             weight: 6,
                //             opacity: 1
                //         })
                //         return cir
                //     }
                // }).addTo(this.map);
            },
            setStart() {
                // this.map.off('click')
                this.map.on('touchend');
                this.map.on('click', (res) => {
                    // if (this.startPoint) {
                    //     this.map.removeLayer(this.startPoint)
                    // }
                    var startIcon = L.icon({
                        iconUrl: require('../assets/start.png'),
                        iconSize: [38, 38],
                        iconAnchor: [22, 38]
                    });
                    // this.startPoint = L.marker(res.latlng, {icon: startIcon}).addTo(this.map);
                    this.startPoint = new mapboxgl.Marker().setLngLat(new mapboxgl.LngLat(res.lngLat.lng, res.lngLat.lat)).addTo(this.map);
                    console.log(this.startPoint);
                })
            },
            setEnd() {
                this.map.on('touchend');
                // this.map.on('click', (res) => {
                //     if (this.endPoint) {
                //         this.map.removeLayer(this.endPoint)
                //     }
                //
                //     this.endPoint = new mapboxgl.Marker().setLngLat(new mapboxgl.LngLat(res.lngLat.lng,res.lngLat.lat)).addTo(this.map);
                //     console.log(this.endPoint);
                // })
            },
            routeAnalysis() {
                this.map.off("click");

                var lastLine = null
                let points = []
                points.push(this.startPoint._latlng.lng.toString() + ',' + this.startPoint._latlng.lat.toString())
                points.push(this.endPoint._latlng.lng.toString() + ',' + this.endPoint._latlng.lat.toString())
                axios({
                    url: "http://192.168.0.121:3000/iserver/services/mgs-networkanalyst/rest/domainComponents/NetworkAnalystServiceImpl/findPathResult.json",
                    method: 'GET',
                    params: {
                        arg0: {
                            "datasetName": 'Rnanjing_Network',
                            "datasourceName": 'Rnanjing',
                            "points": points
                        }
                    }
                }).then(res => {
                    // console.log(res);
                    // console.log(JSON.stringify(res));
                    let latlngs = res.data.result.routes.map(res => {
                        return [res.Y, res.X]
                    })
                    if (lastLine) {
                        map.removeLayer(lastLine)
                    }
                    lastLine = L.polyline(latlngs, {color: 'rgb(51,136,255)', weight: 3}).addTo(this.map);
                    // L.polyline(latlngs, {color: 'rgb(51,136,255)',weight: 3}).addTo(map);
                    this.imitatePointList = res.data.result.pList;
                    this.imitateGuides = res.data.result.guides;
                    this.imitateRoutes = res.data.result.routes;

                    // 插入起始点和终点
                    this.imitatePointList.splice(0, 0, {
                        X: this.startPoint._latlng.lng,
                        Y: this.startPoint._latlng.lat,
                        M: 0
                    });
                    this.imitatePointList.push({
                        X: this.endPoint._latlng.lng,
                        Y: this.endPoint._latlng.lat,
                        M: this.imitatePointList[this.imitatePointList.length - 1].M
                    })
                }).catch(e => {
                    console.log(e);
                })
            },
            imitateNavigation() {
                this.isShowRoutePanel = false;
                this.isShowNavConPanel = true;
                let imitatePointList = this.imitatePointList;
                let imitateGuides = this.imitateGuides;
                let imitateRoutes = this.imitateRoutes;
                let i = 0
                let guide = {}
                let j = 0
                var msg
                guide = imitateGuides[j]
                clearInterval(this.imitateTime)
                //图标移动
                this.imitatePoint = L.marker([imitatePointList[i].Y, imitatePointList[i].X], {icon: this.myIcon}).addTo(this.map);
                // 展示导航信息
                let a = this.formatSecToDate((imitatePointList.length - i) * 2000 / 1000)
                let b = imitatePointList[imitatePointList.length - 1].M - imitatePointList[i].M
                $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米')
                if (guide.turnType) {
                    $("#Tips").html(guide.Guide + '后' + guide.turnType)
                }
                switch (guide.turnType) {
                    case '直行':

                        this.isShowStraight = true;
                        this.isShowRight = false;
                        this.isShowLeft = false;
                        setTimeout(function () {
                            this.isShowStraight = false;
                        }, 4000)
                        break;
                    case '左转':
                        this.isShowStraight = false;
                        this.isShowRight = false;
                        this.isShowLeft = true;

                        setTimeout(function () {
                            this.isShowLeft = false;
                        }, 4000)
                        break;
                    case '右转':
                        this.isShowStraight = false;
                        this.isShowRight = true;
                        this.isShowLeft = false;

                        setTimeout(function () {
                            this.isShowRight = false;
                        }, 4000)
                        break;
                }
                if (guide.turnType) {
                    msg = new window.SpeechSynthesisUtterance(guide.Guide + '后' + guide.turnType);
                    window.speechSynthesis.speak(msg);
                }
                i++
                j++
                guide = imitateGuides[j]
                this.imitateTime = setInterval(() => {
                    if (this.imitatePoint) {
                        this.map.removeLayer(this.imitatePoint)
                    }
                    //图标移动
                    var myIcon = L.icon({
                        iconUrl: require('../assets/marker-icon.png'),
                        iconSize: [24, 36],
                        iconAnchor: [12, 36],
                        popupAnchor: [-3, -76]
                    });
                    this.imitatePoint = L.marker([imitatePointList[i].Y, imitatePointList[i].X], {icon: myIcon}).addTo(this.map);

                    let a = this.formatSecToDate((imitatePointList.length - i) * 2000 / 1000)
                    let b = this.imitatePointList[imitatePointList.length - 1].M - imitatePointList[i].M
                    $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米')

                    // 展示导航信息
                    if (imitatePointList[i].M >= guide.M) {
                        if (guide.turnType) {
                            $("#Tips").html(guide.Guide + '后' + guide.turnType)
                        }
                        switch (guide.turnType) {
                            case '直行':
                                this.map.mapboxLayer._jumpToMap(0, 30)
                                this.isShowStraight = true;
                                this.isShowRight = false;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    this.isShowStraight = false;
                                }, 4000)
                                break;
                            case '左转':
                                this.map.mapboxLayer._jumpToMap(0, 60)
                                this.isShowStraight = false;
                                this.isShowRight = false;
                                this.isShowLeft = true;
                                setTimeout(function () {
                                    this.isShowLeft = false;
                                }, 4000)
                                break;
                            case '右转':
                                this.map.mapboxLayer._jumpToMap(0, 90)
                                this.isShowStraight = false;
                                this.isShowRight = true;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    this.isShowRight = false;
                                }, 4000)
                                break;
                        }
                        if (guide.turnType) {
                            msg = new window.SpeechSynthesisUtterance(guide.Guide + '后' + guide.turnType);
                            window.speechSynthesis.speak(msg);
                        }
                        j++
                        guide = imitateGuides[j]
                        if (j >= imitateGuides.length - 1) {
                            j = 0
                            setTimeout(function () {
                                $("#Tips").html('')
                                $("#timesAdistance").html('')
                            }, 4000)

                        }
                    }
                    i++
                    if (i >= imitatePointList.length) {
                        let that = this;
                        this.isShowStraight = false;
                        this.isShowRight = false;
                        this.isShowLeft = false;
                        clearInterval(this.imitateTime)
                        this.map.removeLayer(this.imitatePoint)
                        setTimeout(function () {
                            msg = new window.SpeechSynthesisUtterance(imitateGuides[imitateGuides.length - 1].Guide);
                            window.speechSynthesis.speak(msg);
                            that.imitateDel()
                        }, 5000)
                    }
                }, 2000)
            },
            mNavigation() {

            },

            // 退出模拟导航
            imitateDel() {
                clearInterval(this.imitateTime)
                // if (myLocation) {
                //     clearInterval(myLocation)
                // }
                this.map.mapboxLayer._jumpToMap(0, 0);
                this.map.removeLayer(this.imitatePoint)
                i = 0
                j = 0
                $("#Tips").html('')
                $("#timesAdistance").html('')
            },
            // 暂停模拟导航
            imitateStop() {
                clearInterval(this.imitateTime)
            },
            // 继续模拟导航
            imitateGo() {
                console.log(i, j)
                this.imitateTime = setInterval(() => {
                    if (this.imitatePoint) {
                        this.map.removeLayer(this.imitatePoint)
                    }
                    this.imitatePoint = L.marker([this.imitatePointList[i].Y, this.imitatePointList[i].X]).addTo(this.map);

                    let a = this.formatSecToDate((this.imitatePointList.length - i) * 2000 / 1000)
                    let b = this.imitatePointList[this.imitatePointList.length - 1].M - this.imitatePointList[i].M
                    $("#timesAdistance").html('剩余时间：' + a + ',' + '剩余距离：' + b + '米')
                    // 展示导航信息
                    if (this.imitatePointList[i].M >= guide.M) {
                        if (guide.turnType) {
                            $("#Tips").html(guide.Guide + '后' + guide.turnType)
                        }
                        switch (guide.turnType) {
                            case '直行':
                                this.isShowStraight = true;
                                this.isShowRight = false;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    $("#turnTipsZHI").hide()
                                }, 4000)
                                break;
                            case '左转':
                                this.isShowStraight = false;
                                this.isShowRight = true;
                                this.isShowLeft = false;
                                setTimeout(function () {
                                    $("#turnTipsZUO").hide()
                                }, 4000)
                                break;
                            case '右转':
                                this.isShowStraight = false;
                                this.isShowRight = false;
                                this.isShowLeft = true;
                                setTimeout(function () {
                                    $("#turnTipsYOU").hide()
                                }, 4000)
                                break;
                        }
                        if (guide.turnType) {
                            msg = new SpeechSynthesisUtterance(guide.Guide + '后' + guide.turnType);
                            window.speechSynthesis.speak(msg);
                        }
                        j = j + 1
                        guide = imitateGuides[j]
                        if (j >= imitateGuides.length - 1) {
                            j = 0
                            setTimeout(function () {
                                $("#Tips").html('')
                                $("#timesAdistance").html('')
                            }, 4000)
                        }
                    }
                    i = i + 1
                    if (i >= this.imitatePointList.length) {
                        clearInterval(this.imitateTime)
                        this.map.removeLayer(this.imitatePoint)
                        setTimeout(function () {
                            msg = new SpeechSynthesisUtterance(this.imitateGuides[this.imitateGuides.length - 1].Guide);
                            window.speechSynthesis.speak(msg);
                            this.imitateDel()
                        }, 5000)
                    }
                }, 2000)
            },
            formatTooltip(val) {
                return val / 100;
            },
            testPitch() {
            },
            //秒转时分秒
            formatSecToDate(sec) {
                if (!sec) {
                    return '-'
                }
                var min = Math.floor(sec % 3600);//分钟
                return Math.floor(sec / 3600) + "时" + Math.floor(min / 60) + "分" + sec % 60 + "秒";
            },

            chulishuju(data) {
                let featureArray = [];
                for (let i in data) {
                    let feature = {
                        type: data[i].type,
                        geomety: {
                            type: data[i].geometry.type,
                            coordinates: data[i].geometry.coordinates
                        }
                    }
                    featureArray.push(feature);
                }
                return featureArray;
            }

        }
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
    }

    #top {
        position: relative;
        top: 0;
        right: 0;
        z-index: 99999;
        display: none;
    }

    .Tips {
        position: relative;
        width: 100%;
        background: #000;
        max-height: 30%;
        overflow: auto;
        padding: 10px;
        color: #fff;
        height: 40px;

    }

    #timesAdistance {
        position: relative;
        right: 0;
        width: 100%;
        background: #000;
        max-height: 30%;
        overflow: auto;
        padding: 10px;
        color: #fff
    }

    #turnTips {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
    }

    #turnTips > img {
        width: 80px;
        height: 80px;
    }

    #btnControl {
        position: absolute;
        top: 30%;
        left: 0;
        z-index: 99999;
    }

    #btnControl > div {
        display: flex;
        flex-direction: column;
    }

    #btnControl button {
        width: 100px;
    }

    #barControl {
        position: absolute;
        width: 100px;
        height: 100px;
        bottom: 0;
        display: flex;
        justify-content: center;
        border: 1px solid red;
        z-index: 999;
    }


</style>